﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using CDFPreliminaryResults;
using t_TestingLibrary;
using System.ComponentModel.Composition;
using PaperRenderingInterfaces;
using System.IO;
using DeepZoomPivotConstructor.PivotLib;
using System.Diagnostics;

namespace t_CDFPreliminaryResults
{
    [TestClass]
    public class t_ScanQCDIndexPage
    {
        [TestInitialize]
        public void TestSetup()
        {
            Utilities.MyClassInit();
        }

        [TestCleanup]
        public void TestCleanup()
        {
            Utilities.MyClassDone();
        }

        /// <summary>
        /// Load a file instead of accessing the web.
        /// </summary>
        [Export(typeof(IWebAccess))]
        private class LoadAFile : IWebAccess
        {
            public List<FileInfo> theFileToLoad = new List<FileInfo>();
            private int index = 0;

            public string GetUriAsString(Uri whatToLoad)
            {
                int current = index;
                index += 1;
                if (index >= theFileToLoad.Count)
                {
                    index = theFileToLoad.Count - 1;
                }
                if (theFileToLoad[current].Exists)
                {
                    using (var reader = theFileToLoad[current].OpenText())
                    {
                        return reader.ReadToEnd();
                    }
                }
                else
                {
                    return null;
                }
                throw new NotImplementedException();
            }


            public DateTime? GetLastModificationTime(Uri whatToCheck)
            {
                throw new NotImplementedException();
            }
        }

        /// <summary>
        /// Render a single image each time we are called.
        /// </summary>
        [Export(typeof(IPaperRenderEngine))]
        class DummyRender : IPaperRenderEngine
        {
            public System.Collections.Generic.IEnumerable<PivotImage> Render(string renderName, string renderAddress)
            {
                if (renderName == "MasterHTMLRenderHTMLAndFurther")
                {
                    PivotImage pmi = new PivotImage(null);
                    Trace.WriteLine("Rendering: " + renderName + " - " + renderAddress);
                    /// We get the note title from the page
                    if (AddTitle)
                    {
                        pmi.Add("Note Title", "Nothing Doing");
                    }
                    yield return pmi;
                }
            }

            public bool AddTitle { get; set; }

            public DummyRender()
            {
                AddTitle = true;
            }
        }

        /// <summary>
        /// Hunt throught the metadata!
        /// </summary>
        /// <typeparam name="T1"></typeparam>
        /// <param name="pmf"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        private T1[] FindMetadata<T1>(PivotImage pmf, string p)
            where T1 : PivotMetadataBase
        {
            var md = from m in pmf
                     where m.Name == p && m.GetType() == typeof(T1)
                     let masType = (T1)m
                     where masType != null
                     select masType;
            return md.ToArray();
        }

        [TestMethod]
        public void TestCTor()
        {
            ScanQCDIndexPage s = new ScanQCDIndexPage();
        }

        [TestMethod]
        public void TestScanQCDPage()
        {
            ScanQCDIndexPage target = new ScanQCDIndexPage();
            var laf = new LoadAFile();
            laf.theFileToLoad.Add(new FileInfo("..\\..\\..\\t_CDFPreliminaryResults\\qcd.html"));
            laf.theFileToLoad.Add(new FileInfo("..\\..\\..\\t_CDFPreliminaryResults\\qcd_abstract.html"));
            Utilities.AddPart(laf);
            Utilities.AddPart(new DummyRender());
            Utilities.Compose(target);

            var result = target.Render("http://www-cdf.fnal.gov/physics/new/qcd/QCD_Overview.html");
            var results = result.ToArray();

            Assert.AreEqual(14, results.Count(), "Incorrect number of links scanned!");
            Assert.IsTrue(results.All(pmi => pmi.Where(md => md.Name == "Note Title").Count() > 0), "Some figures don't have a title!");
        }

        [TestMethod]
        public void TestCheckForAbstract()
        {
            ScanQCDIndexPage target = new ScanQCDIndexPage();
            var laf = new LoadAFile();
            laf.theFileToLoad.Add(new FileInfo("..\\..\\..\\t_CDFPreliminaryResults\\qcd.html"));
            laf.theFileToLoad.Add(new FileInfo("..\\..\\..\\t_CDFPreliminaryResults\\qcd_abstract.html"));
            Utilities.AddPart(laf);
            Utilities.AddPart(new DummyRender());
            Utilities.Compose(target);

            var result = target.Render("http://www-cdf.fnal.gov/physics/new/qcd/QCD_Overview.html");
            var results = result.ToArray();

            var abstractFacets = from r in result
                                 from f in r
                                 where f.Name == "Abstract"
                                 select f;

            Assert.AreEqual(results.Length, abstractFacets.Count(), "Expect the same number of facets with abstract in them as we do results");
        }

        [TestMethod]
        public void TestDoQCDWhenNoHTMLTitle()
        {
            ScanQCDIndexPage target = new ScanQCDIndexPage();
            var laf = new LoadAFile();
            laf.theFileToLoad.Add(new FileInfo("..\\..\\..\\t_CDFPreliminaryResults\\qcd.html"));
            laf.theFileToLoad.Add(new FileInfo("..\\..\\..\\t_CDFPreliminaryResults\\qcd_abstract.html"));
            Utilities.AddPart(laf);
            Utilities.AddPart(new DummyRender() { AddTitle = false });
            Utilities.Compose(target);

            var result = target.Render("http://www-cdf.fnal.gov/physics/new/qcd/QCD_Overview.html");
            var results = result.ToArray();

            Assert.AreEqual(14, results.Count(), "Incorrect number of links scanned!");
            Assert.IsTrue(results.All(pmi => pmi.Where(md => md.Name == "Note Title").Count() > 0), "Some figures don't have a title!");
            Assert.IsFalse((results[0].Where(md => md.Name == "Note Title").First() as PivotMetadataString).Value.Contains("nbsp"), "The title seems to contain a non-breaking space");
        }
    }
}
